package com.wwg.component.serial_num;

import com.wwg.util.WWGAssertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串相关方法
 */
public class StringUtil {

	private static final Logger logger = LoggerFactory.getLogger(StringUtil.class);

	private StringUtil(){}

	/**
	 * 将以逗号分隔的字符串转换成字符串数组
	 * @param valStr
	 * @return String[]
	 */
	public static String[] StrList(String valStr){
	    int i = 0;
	    String TempStr = valStr;
	    String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()];
	    valStr = valStr + ",";
	    while (valStr.indexOf(',') > 0)
	    {
	        returnStr[i] = valStr.substring(0, valStr.indexOf(','));
	        valStr = valStr.substring(valStr.indexOf(',')+1 , valStr.length());
	        
	        i++;
	    }
	    return returnStr;
	}
	
	 /**
		 * 检测字符串是否不为空(null,"","null")
		 * @param s
		 * @return 不为空则返回true，否则返回false
		 */
		public static boolean notEmpty(String s){
			return s!=null && !"".equals(s) && !"null".equals(s) && !"undefined".equals(s);
		}
		/**
		 * 检测字符串是否为空(null,"","null")
		 * @param s
		 * @return 为空则返回true，不否则返回false
		 */
		public static boolean isEmpty(String s){
			return s==null || "".equals(s) || "null".equals(s);
		}
		
		/**
		 * 获取当前时间
		 * @return
		 * @throws Exception 
		 * @throws ParseException 
		 */
		public static Date getDateNow()
		{
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 		format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
	 		String str=format.format(new Date());
	 		Date dd=null;
			try {
				 dd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
			} catch (Exception  e) {
				logger.error(e.getMessage());
			}	
			return dd;
		}
		
		public static String formatData_yyyyMMddHHmmss(Date date) {
			if(null==date)
			{
				return  null;
			}
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return format.format(date);
			
		}
		
		
		public static String formatData_yyyyMMdd(Date date) {
			if(null==date)
			{
				return  null;
			}
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
			return format.format(date);
			
		}
		public static String formatDatetToyyyyMMdd(Date date) {
		if(null==date)
		{
			return  null;
		}
		SimpleDateFormat format =  new SimpleDateFormat("yyyyMMdd");
		return format.format(date);

	}
		
		/**
		 * 随机生成六位数验证码 
		 * @return
		 */
		public static int getRandomNum(){
			 Random r = new Random();
			 return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
		}
	/**
	 * 采用正则表达式将包含有 单引号(')，分号(;) 和 注释符号(--)的语句给替换
	 * @return String
	 */
	public static String TransactSQLInjection(String str)
	{
		return str.replaceAll(".*([';]+|(--)+).*", " ");
	}

	/**
	 * 判断一个对象所有的属性是否为空;注：只对String 有效
	 * @param bean
	 * @return
	 */
	public static boolean checkFieldValueNull(Object bean) {

			if (bean == null) {
				return true;
			}
			ArrayList<String> list=StringUtil.ConvertObjToList(bean);
			if(list.size()>0)
			{
				for(int i=0;i<list.size();i++)
				{
					if(StringUtil.isEmpty(list.get(i)))
					{
						return true;
					}
				}
			}
			return false;
		}

	/**
	 * 对象转为list
	 * @param obj
	 * @return
	 */
	public static ArrayList ConvertObjToList(Object obj){
		ArrayList<String> list=new ArrayList<String>();
		if (obj == null)
			return null;
		Field[] fields = obj.getClass().getDeclaredFields();
		try {
			for(int i=0;i<fields.length;i++){
				try {
					Field f = obj.getClass().getDeclaredField(fields[i].getName());
					f.setAccessible(true);
					Object o = f.get(obj);
					list.add(o.toString());
				} catch (NoSuchFieldException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 时间转date
	 */
	public static Date stringToDate(String dateString,String dateFormat){
	try
	{	if(StringUtil.notEmpty(dateString)&& StringUtil.notEmpty(dateFormat))
	{
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = sdf.parse(dateString);
		return  date;}else {
		return null;
	}
	}
	catch (ParseException e)
	{
		System.out.println(e.getMessage());
		return null;
	}
	}
	/**
	 * 时间转date
	 */
	public static Date stringToDateMore(String time){
		Date ctime = null;
		try {
			SimpleDateFormat formatter;
			formatter= new SimpleDateFormat ("yyyyMMdd");
			time=time.trim() ;
			if(time.indexOf("-")>-1&&(time.indexOf(" ")<0)){
                formatter = new SimpleDateFormat ("yyyy-MM-dd");
            }else if (time.indexOf("/")>-1&&(time.indexOf(" ")<0))
            {
                formatter = new SimpleDateFormat ("yyyy/MM/dd");
            }
            else if((time.indexOf("/")>-1) &&(time.indexOf(" ")>-1)){
                formatter = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
            }
            else if((time.indexOf("-")>-1) &&(time.indexOf(" ")>-1)){
                formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
            }else if((time.indexOf(" ")<0&&time.length()==14)){
                formatter = new SimpleDateFormat ("yyyyMMddHHmmss");
            }

			ParsePosition pos = new ParsePosition(0);
			ctime = formatter.parse(time, pos);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return ctime;
	}
	
	  
	/**  
	 * @description 将字符串 sourceStr中的"{}"替换成replacement变量
	 * @param sourceStr 原字符串
	 * @param replacement 替换字符串
	 * @return sourceStr
	 * @author yyh  
	 * @date 2019年3月21日   上午10:52:28
	 */  
	public static String wsnReplace(String sourceStr, String... replacement) {
		final String expr = "\\{ *\\}";
		Pattern pattern = Pattern.compile(expr);
		Matcher matcher = pattern.matcher(sourceStr);
		for (String str : replacement) {
			sourceStr = matcher.replaceFirst(str);
			matcher = pattern.matcher(sourceStr);
		}
		return sourceStr;
	}
	
	  
	/**  
	 * @description 去除前后空格
	 * @param str
	 * @return
	 * @author yyh  
	 * @date 2019年5月28日   下午3:08:02
	 */  
	public static String trim(String str) {
		if(WWGAssertUtil.isEmpty(str)){
			return str;
		}
		return str.trim();
	}

	/**
	 * @description 去除前后给定的字符
	 * @param srcStr
	 * @param splitter
	 * @return
	 * @author zw
	 * @date 2020-07-24
	 */
	public static String trimBothEndsChars(String srcStr, String splitter) {
		if(WWGAssertUtil.isEmpty(srcStr)){
			return srcStr;
		}
		String regex = "^" + splitter + "*|" + splitter + "*$";
		return srcStr.replaceAll(regex, "");
	}
}
